package com.shop.controller;

import com.shop.base.BaseController;
import com.shop.result.ResultVO;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.Objects;
import java.util.UUID;

/**
 * @author XCH
 * @date 2025 - 05 - 28
 */
@RestController
public class UploadController extends BaseController {
    @PostMapping("/images")
    public ResultVO upload(@RequestParam("file") MultipartFile file) throws IOException {
        // 校验文件是否为空
        if (file.isEmpty()) {
            return error("上传失败，文件为空");
        }

        // 获取文件原始名和后缀
        String originalFilename = file.getOriginalFilename();
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFileName = UUID.randomUUID().toString() + fileExtension;

        // 构建保存路径
        File uploadDir = new File("E:/java_2025_05/shopping/shop-common/src/main/resources/static/images/product");
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        // 保存文件
        Path savePath = FileSystems.getDefault().getPath(uploadDir.getAbsolutePath(), newFileName);
        file.transferTo(savePath.toFile());

        // 可根据实际需要返回完整 URL 或文件名
        String url = "http://localhost:8080/images/product/" + newFileName;
        return success("上传成功", url);
    }
    @PostMapping("/headImage")
    public ResultVO uploadHeadImage(@RequestParam("file") MultipartFile file) throws IOException {
        // 校验文件是否为空
        if (file.isEmpty()) {
            return error("上传失败，文件为空");
        }

        // 获取文件原始名和后缀
        String originalFilename = file.getOriginalFilename();
        String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String newFileName = UUID.randomUUID().toString() + fileExtension;

        // 构建保存路径
        File uploadDir = new File("E:/java_2025_05/shopping/shop-common/src/main/resources/static/images/user");
        if (!uploadDir.exists()) {
            uploadDir.mkdirs();
        }

        // 保存文件
        Path savePath = FileSystems.getDefault().getPath(uploadDir.getAbsolutePath(), newFileName);
        file.transferTo(savePath.toFile());

        // 可根据实际需要返回完整 URL 或文件名
        String url = "http://localhost:8080/images/user/" + newFileName;
        return success("上传成功", url);
    }

}
